﻿using CefSharp;
using CefSharp.WinForms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static 千牛批量开票助手.Func.Configs;
using static 千牛批量开票助手.Func.Threads;
using static 千牛批量开票助手.Func.Hooks;
using Win64MKC;

namespace 千牛批量开票助手
{
    public partial class FrmMain : Form
    {
        // 浏览器设置
        private CefSettings CEF_SETTINGS = new CefSettings
        {
            Locale = "zh-CN",
            AcceptLanguageList = "zh-CN",
            MultiThreadedMessageLoop = true
        };

        private LoginCls LOGIN_CLS;
        private Thread THREAD_CHECK_LOGIN_AND_JS_ADD;
        private Thread THREAD_READ_PDF;
        private Thread THREAD_IDENTIFY_CHECK;
        private Thread THREAD_CLICK_ALLOW;
        private Thread THREAD_UPLOAD;

        [Obsolete]
        public FrmMain()
        {
            InitializeComponent();
            Cef.Initialize(CEF_SETTINGS);
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            // 读取登录账号信息
            ConfigCls configCls = ReadConfig();
            if (configCls != null)
            {
                TxtUsr.Text = configCls.FUsr;
                TxtPwd.Text = configCls.FPwd;
                TxtInvoicePath.Text = configCls.FInvoicePath;
                TxtBackupPath.Text = configCls.FBackupPath;
                NudLoopTime.Value = configCls.FLoopTime;
                NudLoopQty.Value = configCls.FLoopQty;
            }

            // 默认登录状态为[未登录]
            CboStatus.Enabled = false;
            CboStatus.Text = "未登录";

            // 创建多线程对象
            LOGIN_CLS = new LoginCls
            {
                FMainForm = this,
                FCboStatus = CboStatus,
                FGrpUsr = GrpUsr,
                FDgvList = DgvList,
                FNudLoopTime = NudLoopTime,
                FNudLoopQty = NudLoopQty,
                FChbRunStatus = ChbRunStatus,
                FChbDataLock = ChbDataLock,
                FChbIdentifyStatus = ChbIdentifyStatus,
                FTxtInvoicePath = TxtInvoicePath,
                FTxtBackupPath = TxtBackupPath,
                FTxtUsr = TxtUsr,
                FTxtPwd = TxtPwd,
                FSplWeb = SplWeb,
                FBtnRun = BtnRun,
                FLblListCount = LblListCount,
                FWebL = WebL,
                FWebR = WebR
            };
        }

        private void FrmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            // 关闭程序前, 保存配置文件
            SaveConfigMain();

            LOGIN_STATUS = false;
            BtnStop_Click(null, null);
            if (THREAD_CHECK_LOGIN_AND_JS_ADD != null) THREAD_CHECK_LOGIN_AND_JS_ADD.Abort();
            if (THREAD_READ_PDF != null) THREAD_READ_PDF.Abort();
            if (THREAD_IDENTIFY_CHECK != null) THREAD_IDENTIFY_CHECK.Abort();
            if (THREAD_CLICK_ALLOW != null) THREAD_CLICK_ALLOW.Abort();
        }

        [Obsolete]
        private void FrmMain_KeyDown(object sender, KeyEventArgs e)
        {
            // Ctrl + F5 启动
            if (e.Control && e.KeyCode == Keys.F5) { BtnRun.PerformClick(); }
            // Ctrl + F12 停止
            else if (e.Control && e.KeyCode == Keys.F12) { BtnStop.PerformClick(); }
        }

        private void Web_LoadingStateChanged(object sender, LoadingStateChangedEventArgs e)
        {
            if (!e.IsLoading)
            {
                e.Browser.SetZoomLevel(-3);

                // 加载 JS
                if ((sender as ChromiumWebBrowser).Address.ToLower().Contains("einvoice.taobao.com")) AddJS(LOGIN_CLS);
            }
        }

        private void SaveConfigMain()
        {
            SaveConfig(TxtUsr.Text, TxtPwd.Text, TxtInvoicePath.Text, TxtBackupPath.Text, Convert.ToInt32(NudLoopTime.Value), Convert.ToInt32(NudLoopQty.Value));
        }

        private void BtnLogin_Click(object sender, EventArgs e)
        {
            if (CboStatus.Text == "未登录")
            {
                // 点击登录时, 保存配置文件
                SaveConfigMain();

                // 执行登录操作
                GrpUsr.Enabled = false;

                WebL.Load("https://login.taobao.com");

                LOGIN_CLS.FAutoLogin = sender != null;

                THREAD_CHECK_LOGIN_AND_JS_ADD = new Thread(Thread_CheckLoginAndJSAdd);
                THREAD_CHECK_LOGIN_AND_JS_ADD.Start(LOGIN_CLS);
            }
        }

        private void BtnQrLogin_Click(object sender, EventArgs e)
        {
            BtnLogin_Click(null, null);
        }

        private void BtnSelectPath_Click(object sender, EventArgs e)
        {
            Button btn = sender as Button;
            Dictionary<string, TextBox> dictTxt = new Dictionary<string, TextBox>
            {
                { "BtnInovicePath", TxtInvoicePath },
                { "BtnBackupPath", TxtBackupPath }
            };
            FolderBrowserDialog folderBrowser = new FolderBrowserDialog { ShowNewFolderButton = true };
            if (folderBrowser.ShowDialog() == DialogResult.OK)
            {
                dictTxt[btn.Name].Text = folderBrowser.SelectedPath;
                // 修改文件时, 保存配置文件
                SaveConfigMain();
            }
        }

        public class FolderPathCls
        {
            public TextBox FTxtObj { get; set; }
            public string FTips { get; set; }
        }

        private void BtnOpenFolder_Click(object sender, EventArgs e)
        {
            Button btn = sender as Button;
            Dictionary<string, FolderPathCls> dictTxt = new Dictionary<string, FolderPathCls>
            {
                { "BtnOpenInvoice", new FolderPathCls{ FTxtObj = TxtInvoicePath, FTips = "发票文件夹" } },
                { "BtnOpenBackup", new FolderPathCls { FTxtObj = TxtBackupPath, FTips = "备份文件夹" } }
            };
            TextBox txtObj = dictTxt[btn.Name].FTxtObj;
            if (!Directory.Exists(txtObj.Text))
            {
                MessageBox.Show($"{dictTxt[btn.Name].FTips}路径不存在, 请重新选择", "打开文件夹异常", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            Process.Start(txtObj.Text);
        }

        [Obsolete]
        private void BtnRun_Click(object sender, EventArgs e)
        {
            // 启动线程时, 保存配置文件
            SaveConfigMain();

            // 检查淘宝账号是否登录成功
            if (CboStatus.Text == "未登录")
            {
                TabCtrls.SelectedTab = TabpSetting;
                MessageBox.Show("淘宝账号未登录, 请登录后重试", "启动异常", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 检查文件夹路径是否正确
            List<FolderPathCls> folderPaths = new List<FolderPathCls>
            {
                new FolderPathCls { FTxtObj = TxtInvoicePath, FTips = "发票文件夹" },
                new FolderPathCls { FTxtObj = TxtBackupPath, FTips = "备份文件夹" }
            };

            for (int i = 0; i < folderPaths.Count; i++)
            {
                FolderPathCls folderPathCls = folderPaths[i];
                if (!Directory.Exists(folderPathCls.FTxtObj.Text))
                {
                    TabCtrls.SelectedTab = TabpSetting;
                    folderPathCls.FTxtObj.Focus();
                    MessageBox.Show($"{folderPathCls.FTips}路径不存在, 请重新选择", "启动异常", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                } 
            }

            if (!IDENTIFY_STATUS)
            {
                if (!RUN_STATUS)
                {
                    BtnRun.Enabled = false;
                    BtnRun.Text = "运行中...";
                    LblListCount.Text = $"列表总数：0";

                    RUN_STATUS = true;
                    DATA_LOCK = false;

                    WebL.Reload();
                    WebR.Reload();

                    // 启动运行后设置页失效
                    GrpUsr.Enabled = false;
                    GrpPath.Enabled = false;
                    GrpAuto.Enabled = false;

                    // 启动运行后, 页面默认跳转至发票列表
                    TabCtrls.SelectedTab = TabpList;
                    // 清空列表
                    DgvList.Rows.Clear();

                    // 启动 [发票 PDF 读取] 线程
                    THREAD_READ_PDF = new Thread(Thread_ReadPDF);
                    THREAD_READ_PDF.Name = "ReadPdf";
                    THREAD_READ_PDF.Start(LOGIN_CLS);

                    // 启动人工检验检测线程
                    THREAD_IDENTIFY_CHECK = new Thread(Thread_IdentifyCheck);
                    THREAD_IDENTIFY_CHECK.Name = "IdentifyCheck";
                    THREAD_IDENTIFY_CHECK.Start(LOGIN_CLS);

                    // 启动 [点击同意] 线程
                    THREAD_CLICK_ALLOW = new Thread(Thread_ClickAllow);
                    THREAD_CLICK_ALLOW.Name = "ClickAllow";
                    THREAD_CLICK_ALLOW.Start(LOGIN_CLS);

                    // 启动 [点击上传] 线程
                    THREAD_UPLOAD = new Thread(Thread_Upload);
                    THREAD_UPLOAD.Name = "Upload";
                    THREAD_UPLOAD.Start(LOGIN_CLS);
                }
                else
                {
                    MessageBox.Show("列表正在运行中, 请勿重复运行", "运行提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else
            {
                BtnRun.Enabled = false;
                BtnRun.Text = "运行中...";

                // 因为人工验证而暂停, 执行页面刷新重启
                WebL.Reload();
                WebR.Reload();
            }
        }

        private void BtnStop_Click(object sender, EventArgs e)
        {
            LOGIN_STATUS = false;

            // 停止后运行后设置页恢复
            GrpUsr.Enabled = true;
            GrpPath.Enabled = true;
            GrpAuto.Enabled = true;

            RUN_STATUS = false;
            IDENTIFY_STATUS = false;
            DATA_LOCK = false;

            ChbRunStatus.Checked = false;
            ChbDataLock.Checked = false;
            ChbIdentifyStatus.Checked = false;

            BtnRun.Enabled = true;
            BtnRun.Text = "启动\r\n(Ctrl + F5)";

            LblListCount.Text = $"列表总数：0";

            // 停止线程时, 保存配置文件
            SaveConfigMain();
        }

        private void CboStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            bool flag = (sender as ComboBox).Text == "未登录";

            // 默认仅展示一个浏览器窗口, 淘宝账号登录成功后会展示两个窗口
            SplWeb.Panel2Collapsed = flag;

            // 设置按钮初始状态
            BtnRun.Enabled = !flag;
            BtnStop.Enabled = !flag;
        }
    }
}
